package com.gxs.ea.fileupload.beans.jsf;

import java.io.IOException;
import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.springframework.context.annotation.Scope;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component("loginBean")
@Scope("request")
public class LoginBean implements PhaseListener, Serializable
{
	private String userId;
	private String password;
	
	private void clearFields()
	{
		userId = null;
		password = null;
	}
	
	/**
    *
    * Redirects the login request directly to spring security check.
    * Leave this method as it is to properly support spring security.
    * 
    * @return
    * @throws ServletException
    * @throws IOException
    */
	public String performLogin() throws ServletException, IOException
	{
		boolean hasErrors = false;
		
		if(StringUtils.isEmpty(userId))
		{
			hasErrors = true;
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Invalid Input", "User Id cannot be blank"));
		}
		
		if(StringUtils.isEmpty(password))
		{
			hasErrors = true;
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Invalid Input", "Password cannot be blank"));
		}
		
		if(hasErrors)
			return null;
		System.out.println("====>Info: "+  userId + ":" + password);
		
		 ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
		 ServletRequest request = ((ServletRequest) context.getRequest());
		 System.out.println("--> " + request.getAttribute("j_username") );
		 RequestDispatcher dispatcher = ((ServletRequest) context.getRequest()).getRequestDispatcher("/j_spring_security_check");
	     dispatcher.forward((ServletRequest) context.getRequest(), (ServletResponse) context.getResponse());
  	     FacesContext.getCurrentInstance().responseComplete();
        
  	     clearFields();
  	     // It's OK to return null here because Faces is just going to exit.
	     return null;
	}
	
	@Override
	public void afterPhase(PhaseEvent event) {
    }
	
	/* (non-Javadoc)
     * @see javax.faces.event.PhaseListener#beforePhase(javax.faces.event.PhaseEvent)
     * 
     * Do something before rendering phase.
     */
	@Override
    public void beforePhase(PhaseEvent event) 
    {
        Exception e = (Exception) FacesContext.getCurrentInstance().
          getExternalContext().getSessionMap().get(WebAttributes.AUTHENTICATION_EXCEPTION);
 
        if (e instanceof BadCredentialsException) 
        {
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(WebAttributes.AUTHENTICATION_EXCEPTION, null);
            FacesContext.getCurrentInstance().addMessage(null,     new FacesMessage(FacesMessage.SEVERITY_ERROR,   "Username or password not valid.", "Username or password not valid"));
        }
    }
    
    /* (non-Javadoc)
     * @see javax.faces.event.PhaseListener#getPhaseId()
     * 
     * In which phase you want to interfere?
     */
	@Override
    public PhaseId getPhaseId() {
        return PhaseId.RENDER_RESPONSE;
    }

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	


}
